/**
 * @author shaosong
 * @description
 */
import { Input } from '@nextui-org/react'
import React, { useEffect } from 'react'
import NextIcon from '../NextIcon'
import { reg } from 'regexp-utils-lib'

export class EmailInputProps {
  defaultValue?: string
  value?: string
}

const EmailInput: React.FC<EmailInputProps> = props => {
  const [value, changeValue] = React.useState<string | undefined>(
    props?.defaultValue
  )
  const validateEmail = (value: string | undefined) => value?.match(reg.mail)

  const isInvalid = React.useMemo(() => {
    if (!value) return false

    return validateEmail(value) ? false : true
  }, [value])

  useEffect(() => {
    if (props?.value !== value) {
      changeValue(props?.value)
    }
  }, [props?.value])

  return React.useMemo(
    () => (
      <Input
        type="email"
        label="Email"
        isClearable
        isInvalid={isInvalid}
        placeholder="you@example.com"
        errorMessage="Please enter a valid email"
        labelPlacement="outside"
        value={value}
        color={isInvalid ? 'danger' : 'default'}
        startContent={
          <NextIcon
            type="email"
            size={16}
            className="text-default-400 pointer-events-none flex-shrink-0"
          />
        }
        onValueChange={changeValue}
      />
    ),
    [value, isInvalid]
  )
}

export default EmailInput
